package com.allm.ai.common.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.allm.ai.common.entity.AiModel;
import com.allm.ai.common.repository.AiModelRepository;
import com.allm.ai.common.service.AiModelService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * AI模型服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class AiModelServiceImpl implements AiModelService {

    private final AiModelRepository aiModelRepository;

    @Override
    public AiModel createAiModel(AiModel aiModel) {
        if (aiModelRepository.existsByName(aiModel.getName())) {
            throw new RuntimeException("模型名称已存在: " + aiModel.getName());
        }
        log.info("创建AI模型: {}", aiModel.getName());
        return aiModelRepository.save(aiModel);
    }

    @Override
    public AiModel updateAiModel(Long id, AiModel aiModel) {
        AiModel existingModel = aiModelRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("模型不存在: " + id));
        
        // 检查名称是否重复（排除自身）
        if (!existingModel.getName().equals(aiModel.getName()) && 
            aiModelRepository.existsByName(aiModel.getName())) {
            throw new RuntimeException("模型名称已存在: " + aiModel.getName());
        }
        
        // 更新字段
        existingModel.setName(aiModel.getName());
        existingModel.setDisplayName(aiModel.getDisplayName());
        existingModel.setIcon(aiModel.getIcon());
        existingModel.setApiEndpoint(aiModel.getApiEndpoint());
        existingModel.setApiKey(aiModel.getApiKey());
        existingModel.setServiceProvider(aiModel.getServiceProvider());
        existingModel.setModelType(aiModel.getModelType());
        existingModel.setIsFree(aiModel.getIsFree());
        existingModel.setIsActive(aiModel.getIsActive());
        existingModel.setMaxTokens(aiModel.getMaxTokens());
        existingModel.setTemperature(aiModel.getTemperature());
        existingModel.setDescription(aiModel.getDescription());
        
        log.info("更新AI模型: {}", existingModel.getName());
        return aiModelRepository.save(existingModel);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<AiModel> findById(Long id) {
        return aiModelRepository.findById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<AiModel> findByName(String name) {
        return aiModelRepository.findByName(name);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AiModel> findAll() {
        return aiModelRepository.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Page<AiModel> findByConditions(String name, String serviceProvider, 
                                        String modelType, Boolean isActive, 
                                        Boolean isFree, Pageable pageable) {
        return aiModelRepository.findByConditions(name, serviceProvider, modelType, isActive, isFree, pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AiModel> findActiveModels() {
        return aiModelRepository.findByIsActiveTrue();
    }

    @Override
    @Transactional(readOnly = true)
    public List<AiModel> findFreeModels() {
        return aiModelRepository.findByIsFreeTrue();
    }

    @Override
    @Transactional(readOnly = true)
    public List<AiModel> findByServiceProvider(String serviceProvider) {
        return aiModelRepository.findByServiceProvider(serviceProvider);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AiModel> findByModelType(String modelType) {
        return aiModelRepository.findByModelType(modelType);
    }

    @Override
    public void deleteById(Long id) {
        AiModel model = aiModelRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("模型不存在: " + id));
        log.info("删除AI模型: {}", model.getName());
        aiModelRepository.deleteById(id);
    }

    @Override
    public AiModel toggleActive(Long id) {
        AiModel model = aiModelRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("模型不存在: " + id));
        model.setIsActive(!model.getIsActive());
        log.info("切换AI模型状态: {} -> {}", model.getName(), model.getIsActive());
        return aiModelRepository.save(model);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean existsByName(String name) {
        return aiModelRepository.existsByName(name);
    }

    @Override
    public List<AiModel> findByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        return aiModelRepository.findAllById(ids);
    }
} 